<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use pay\Wxservicer;
use think\Controller;
use think\Db;

class  Weixin extends Base  {
    /**
     * 回调验证
     * @return array|string
     */
    public function huidiao(){
        // 获取xml
        $xml=file_get_contents('php://input', 'r');
        $wx = new Wxservicer(config('wechat_servicer'));
        // 转成php数组
        $getInfo = $wx->toArray($xml);
//        $this->write_admin_log($getInfo);
        // 保存原sign
        $data_sign = $getInfo['sign'];
        // sign不参与签名
        unset($getInfo['sign']);
        $sign = $wx->makeSign($getInfo);
        // 判断签名是否正确  判断支付状态
        if ($sign === $data_sign && $getInfo['return_code'] == 'SUCCESS' && $getInfo['result_code'] == 'SUCCESS') {
            $num = $getInfo['out_trade_no']; // 订单号
            if(strpos($num, 'BG') !== false){
                $num_type = 1; // 礼包订单
            }elseif (strpos($num, 'BZ') !== false){
                $num_type = 2; // 赠品订单
            }elseif (strpos($num, 'KC') !== false){
                $num_type = 3; // 课程订单
            }elseif (strpos($num, 'SK') !== false){
                $num_type = 4; // 收款订单
            }elseif (strpos($num, 'PB') !== false){
                $num_type = 5; // 私人订制套餐购买订单
            }elseif (strpos($num, 'TH') !== false){
                $num_type = 6; // 特惠商场礼包订单
            }

            if($num_type == 1){
                $order = Db::table('up_bo_orderg')->where('bog_number', $num)
                    ->join('up_bo_giftbag', 'bog_gift_id = gift_id', 'LEFT')
                    ->field('bog_id, bog_status, gift_indate, bog_user_id, bog_gift_id, 
                        bog_total_price, bog_invite, gift_is_zy, bog_is_pay')
                    ->find();

                $limit = $order['gift_indate'] - 2;
                $indate = date('Y-m', strtotime("last day of +{$limit} months"));
                if($order['bog_is_pay'] == 1){
                    $user = Db::table('up_u_user')->where('user_id', $order['bog_user_id'])
                        ->field('user_giftbag_invite_other, user_username, user_giftbag_level, 
                            user_rule, user_bo_role, user_giftbag_date')
                        ->find();

                    $up_user = Db::table('up_u_user')
                        ->where('user_invite', $order['bog_invite'])
                        ->where('user_invite', '<>', '0')
                        ->field('user_id, user_giftbag_balance, user_is_giftbag, user_giftbag_level, 
                            user_rule, user_bo_role')
                        ->find();

                    Db::startTrans();
                    try{
                        /**
                         * 如果有上级，并且上级购买过礼包，则上级可以获取相应的奖励
                         * 1.上级服务费   2.入积分明细
                         */
                        if(($up_user && $up_user['user_giftbag_level'] != 1) || $order['bog_invite'] == 'djl9988'){
                            // 服务费金额
                            $fy = Db::table('up_bo_giftbag')->where('gift_id', $order['bog_gift_id'])->value('gift_fy');
                            $fy_balance = $order['bog_total_price'] * $fy / 100;
                            // 上级分佣
                            Db::table('up_u_user')
                                ->update([
                                    'user_id' => $up_user['user_id'],
                                    'user_giftbag_balance' => $fy_balance + $up_user['user_giftbag_balance']
                                ]);
                            // 服务费明细
                            $desc = $user['user_username'] . '-购买礼包服务费';
                            insertBoGiftGagInte($up_user['user_id'], $order['bog_user_id'], 1, $desc, $fy_balance, $up_user['user_giftbag_balance']);
                        }

                        // 增加销量
                        Db::table('up_bo_giftbag')->where('gift_id', $order['bog_gift_id'])->setInc('gift_sale_number');

                        // 修改用户信息
                        $update_user = [
                            'user_id' => $order['bog_user_id'],
                            'user_update_time' => date('Y-m-d H:i:s'),
                            'user_is_giftbag' => 2
                        ];
                        if($order['gift_is_zy'] == 2){ // 非自由创业者
                            if($user['user_giftbag_level'] == 1){ // 普通用户
                                $update_user['user_giftbag_level'] = 2;
                            }
                        }else{ // 自由创业者
                            if($user['user_giftbag_level'] != 3){
                                $update_user['user_giftbag_level'] = 3;
                            }
                            if($user['user_bo_role'] == 1){
                                $update_user['user_bo_role'] = 2;
                            }
                            if($user['user_rule'] == '1'){
                                $update_user['user_rule'] = '3';
                            }elseif ($user['user_rule'] == '2'){
                                $update_user['user_rule'] = '2,3';
                            }
                        }

                        if(!$user['user_giftbag_invite_other']){
                            $update_user['user_giftbag_invite_other'] = $order['bog_invite'];
                        }
                        if(!$user['user_giftbag_date']){
                            $update_user['user_giftbag_date'] = date('Y-m-d');
                        }
                        Db::table('up_u_user')->update($update_user);

                        // 修改上级用户身份，上级推广20个丽人礼包，可直接升为自由创业者
                        if($up_user['user_giftbag_level'] == 2){
                            $count = Db::table('up_bo_orderg')
                                ->join('up_bo_giftbag', 'gift_id = bog_gift_id', 'LEFT')
                                ->where('bog_up_user_id', $up_user['user_id'])
                                ->where('gift_is_zy', 2)
                                ->where('bog_is_pay', 2)
                                ->count();
                            if($count == 19){
                                $update_up = [
                                    'user_id' => $up_user['user_id'],
                                    'user_update_time' => date('Y-m-d H:i:s'),
                                ];
                                if($up_user['user_giftbag_level'] != 3){
                                    $update_up['user_giftbag_level'] = 3;
                                }
                                if($up_user['user_bo_role'] == 1){
                                    $update_up['user_bo_role'] = 2;
                                }
                                if($up_user['user_rule'] == '1'){
                                    $update_up['user_rule'] = '3';
                                }elseif ($up_user['user_rule'] == '2'){
                                    $update_up['user_rule'] = '2,3';
                                }
                                Db::table('up_u_user')->update($update_up);
                            }
                        }

                        // 修改订单信息
                        Db::table('up_bo_orderg')->update([
                            'bog_id' => $order['bog_id'],
                            'bog_is_pay' => 2,
                            'bog_status' => 2,
                            'bog_pay_month' => date('Y-m'),
                            'bog_indate' => $indate,
                            'bog_indate_month' => $order['gift_indate'] - 1,
                            'bog_zeng_number' => $order['gift_indate'] - 1,
                            'bog_pay_time' => date('Y-m-d H:i:s'),
                            'bog_up_user_id' => $up_user['user_id']
                        ]);


                        Db::commit();
                        $result = true;
                    }catch (\Exception $e){
                        Db::rollback();
                        $result = false;
                    }
                }else{
                    $result = true;
                }
            }elseif($num_type == 2){
                // 赠品订单回调
                $order = Db::table('up_bo_orderz')->where('boz_number', $num)
                    ->field('boz_id, boz_status, boz_order_id, boz_no, boz_get_type, boz_user_id, boz_is_pay')->find();
                if($order['boz_is_pay'] == 1){
                    $update_zeng = [
                        'boz_id' => $order['boz_id'],
                        'boz_is_pay' => 2,
                        'boz_status' => 2,
                        'boz_pay_time' => date('Y-m-d H:i:s'),
                        'boz_get_month' => date('Y-m')
                    ];

                    $alreadyGet = Db::table('up_bo_orderz')
                        ->where(['boz_order_id' => $order['boz_order_id'], 'boz_is_pay' => 2])
                        ->sum('boz_no');
                    if($alreadyGet + $order['boz_no'] == 11){
                        $update_zeng['boz_eleven'] = '已领11盒面膜';
                    }

                    $giftbag_order = Db::table('up_bo_orderg')
                        ->join('up_u_user', 'user_id = bog_user_id', 'LEFT')
                        ->where('bog_id', $order['boz_order_id'])
                        ->field('user_zeng_get_type, user_id')
                        ->find();

                    Db::startTrans();
                    try{
                        // 更新面膜订单信息
                        Db::table('up_bo_orderz')->update($update_zeng);

                        // 减剩余面膜数量
                        Db::table('up_bo_orderg')->where('bog_id', $order['boz_order_id'])->setDec('bog_zeng_number', $order['boz_no']);

                        // 确定用户面膜可领取的渠道
                        if($giftbag_order['user_zeng_get_type'] == 0){
                            Db::table('up_u_user')->where('user_id', $giftbag_order['user_id'])->setField('user_zeng_get_type', $order['boz_get_type']);
                        }

                        // 日志
                        insertGiftbagLog($order['boz_order_id'], '用户领取面膜扣除', 0, $order['boz_no']);

                        Db::commit();
                        $result = true;
                    }catch (\Exception $e){
                        Db::rollback();
                        $result = false;
                    }
                }else{
                    $result = true;
                }
            }elseif($num_type == 3){
                // 课程订单回调
                $order = Db::table('up_class_order')->where('co_number', $num)
                    ->field('co_user_id, co_class_id, co_total_price, co_number, co_is_pay, co_id')
                    ->find();

                if($order['co_is_pay'] == 1){
                    $class = Db::table('up_class')->where('class_id', $order['co_class_id'])
                        ->field('class_is_forever, class_valid_date')
                        ->find();
                    // 是否已经在报名表中，如果不在插入我报名的课程表&增加课程报名人数，如果在，就更新有效时间
                    $have_apply = Db::table('up_class_apply')
                        ->where(['c_apply_user_id' => $order['co_user_id'], 'c_apply_class_id' => $order['co_class_id']])
                        ->field('c_apply_id, c_apply_class_forever')
                        ->find();
                    if($class['class_is_forever'] == 1){
                        $valid_date = date('Y-m-d', strtotime("+{$class['class_valid_date']}days"));
                    }else{
//                        $valid_date = 0;
                        $valid_date = '';
                    }

                    Db::startTrans();
                    try{
                        if($have_apply){
                            $update_apply = [
                                'c_apply_class_forever' => $class['class_is_forever'],
                                'c_apply_update_time' => date('Y-m-d H:i:s'),
                                'c_apply_valid' => $valid_date
                            ];
                            // 更新有效期
                            Db::table('up_class_apply')->where('c_apply_id', $have_apply['c_apply_id'])->update($update_apply);
                        }else{
                            // 插入报名表
                            $apply = [
                                'c_apply_user_id' => $order['co_user_id'],
                                'c_apply_class_id' => $order['co_class_id'],
                                'c_apply_class_forever' => $class['class_is_forever'],
                                'c_apply_valid' => $valid_date,
                                'c_apply_time' => date('Y-m-d H:i:s')
                            ];
                            Db::table('up_class_apply')->insert($apply);

                            // 更新报名人数
                            Db::table('up_class')->where('class_id', $order['co_class_id'])->setInc('class_apply_number');
                        }

                        Db::table('up_class_order')
                            ->update([
                                'co_id' => $order['co_id'],
                                'co_is_pay' => 2,
                                'co_pay_time' => date('Y-m-d H:i:s')
                            ]);

                        Db::commit();
                        $result = true;
                    }catch (\Exception $e){
                        Db::rollback();
                        $result = false;
                    }

                }else{
                    $result = true;
                }
            }elseif ($num_type == 4){
                // 收款订单回调 transaction_id
                $order = Db::table('up_shou')
                    ->where('shou_number', $num)
                    ->field([
                        'shou_id',
                        'shou_is_pay',
                        'shou_user_id',
                        'shou_project_id',
                        'shou_remark',
                        'shou_price'
                    ])
                    ->find();
                if($order['shou_is_pay'] == 1){

                    $user = Db::table('up_u_user')
                        ->where('user_id', $order['shou_user_id'])
                        ->field([
                            'user_invite',
                            'user_bo_invite_other',
                            'user_bo_role',
                            'user_recharge_price',
                            'user_bo_balance',
                            'user_real_name',
                            'user_up_tz_code',
                            'user_up_up_tz_code',
                            'user_sheng',
                            'user_shi',
                            'user_qu',
                            'user_recharge_balance',
                            'user_big_balance'
                        ])
                        ->find();

                    $upUser = Db::table('up_u_user')
                        ->where('user_invite', $user['user_bo_invite_other'])
                        ->field([
                            'user_bo_role',
                            'user_up_tz_code',
                            'user_up_up_tz_code',
                            'user_tz_code',
                            'user_invite',
                            'user_id',
                            'user_bo_fy_balance',
                            'user_teamer_status',
                            'user_real_name'
                        ])
                        ->find();
                    Db::startTrans();
                    try{
                        // 修改订单状态
                        Db::table('up_shou')->where('shou_id', $order['shou_id'])
                            ->update([
                                'shou_other_number' => $getInfo['transaction_id'],
                                'shou_is_pay' => 2,
                                'shou_pay_time' => date('Y-m-d H:i:s')
                            ]);

                        /**
                         * 1.首批款：变更身份，首批款积分，分佣
                         * 2.补货款：补货款积分，分佣，管理费
                         * 3.活动诚意金：不入积分（已取消此充值款项）
                         * 4.特惠商品：特惠商品积分
                         * 5.家大业大：家大业大积分
                         * 6.其它：不计入积分，只需要支付记录
                         * 7.定金：其它款项积分，不分佣
                         *
                         */
                        if($order['shou_project_id'] == 1){
                            //*********************************   变更我的身份  start  ********************//
                            if($order['shou_price'] == 19800){
                                $boRole = 3; // 团员
                            }else{
                                $boRole = 4; // 团长
                            }

                            if($upUser['user_bo_role'] == 3){ // 如果上级是团员
                                $upTz = $upUser['user_up_tz_code'];
                                $upUpTz = $upUser['user_up_up_tz_code'];
                            }else{
                                $upTz = $upUser['user_tz_code'];
                                $upUpTz = $upUser['user_up_tz_code'];
                            }
                            if($boRole == 3){ // 团员
                                $tzCode = -1; // 团队长编号
                            }else{ // 团长
                                // 第一个未被使用的编号
                                $code = $this->getFirstNoUseTzCode();
                                $tzCode = $code['code']; // 团队长编号
                            }
                            $_ty = $this->getTyCode($upTz);
                            $tyCode = $_ty['user_ty_code'] + 1; // 团员编号

                            $updateUser = [
                                'user_id' => $order['shou_user_id'],
                                'user_bo_role' => $boRole,
                                'user_tz_code' => $tzCode,
                                'user_ty_code' => $tyCode,
                                'user_up_tz_code' => $upTz,
                                'user_up_up_tz_code' => $upUpTz,
                                'user_recharge_price' => $order['shou_price'],
                                'user_is_recharge' => 1,
                                'user_update_time' => date('Y-m-d H:i:s')
                            ];
                            Db::table('up_u_user')->update($updateUser);

                            //******************************  变更上级身份
                            // 如果上级不是团长，并且推广了两个团员，则可以升级成团长
                            $lowerCount = $this->getLowerNumber($upUser['user_invite']);
                            if($upUser['user_bo_role'] != 4 && $lowerCount == 2){
                                // 第一个未被使用的编号
                                $upCode = $this->getFirstNoUseTzCode();
                                $upTzCode = $upCode['code']; // 上级团队长编号

                                $upUserUpdate = [
                                    'user_id' => $upUser['user_id'],
                                    'user_bo_role' => 4,
                                    'user_tz_code' => $upTzCode,
                                    'user_update_time' => date('Y-m-d H:i:s')
                                ];
                                Db::table('up_u_user')->update($upUserUpdate);
                            }
                            //*********************************   变更我的身份  end  ********************//

                            //*********************************   首批款充值   start ********************//
                            // 1.用户积分
                            if($order['shou_remark']){
                                $descFirst = '首批款-' . $order['shou_remark'];
                            }else{
                                $descFirst = '首批款';
                            }
                            $this->insertBoInte($order['shou_user_id'], 1, $descFirst, $order['shou_price'], $user['user_bo_balance'], 0);

                            Db::table('up_u_user')
                                ->where('user_id', $order['shou_user_id'])
                                ->inc('user_bo_total_balance', $order['shou_price'])
                                ->inc('user_bo_balance', $order['shou_price'])
                                ->inc('user_bo_first_balance', $order['shou_price'])
                                ->update();

                            //*********************************   首批款充值   end ********************//

                            //*********************************   首批款分佣   start ********************//
                            // 2.直开分佣
//                            $firstUpRatio = $this->getBoUserSystemFirstRatio(1, $zk, 0, $qd); // 提点比例
                            $firstUpRatio = config('default_first_up_ratio'); // 提点比例
                            $firstUpFy = $order['shou_price'] * $firstUpRatio / 100; // 分佣金额

                            $userFirst = Db::table('up_u_user')
                                ->where('user_id', $order['shou_user_id'])
                                ->field([
                                    'user_up_tz_code',
                                    'user_up_up_tz_code',
                                    'user_real_name'
                                ])
                                ->find();

                            // 直开&团长信息
                            $upFyUser = $this->getFirstFyUser(1, $userFirst['user_up_tz_code'], $userFirst['user_up_up_tz_code'], $upUser);
//                        print_r($upFyUser);
                            if($upFyUser['up_role'] == 4){
                                $firstFyFrom = 1;
                            }else{
                                $firstFyFrom = 0;
                            }
                            $firstUpDesc = $user['user_real_name'] . '首批款-佣金';
                            $this->insertBoFy($upFyUser['user_id'], $order['shou_user_id'], $upFyUser['should_user_id'], $upFyUser['freeze_user_id'], 1, $firstUpDesc, 1, $firstUpFy, $upUser['user_bo_fy_balance'], 0, $upFyUser['hf'], $firstFyFrom, $upFyUser['freeze_name']);

                            Db::table('up_u_user')
                                ->where('user_id', $upFyUser['user_id'])
                                ->inc('user_bo_fy_balance', $firstUpFy)
                                ->inc('user_bo_total_fy_balance', $firstUpFy)
                                ->update();


                            // 3.团长分佣
                            $tzFyUser = $this->getFirstFyUser(2, $userFirst['user_up_tz_code'], $userFirst['user_up_up_tz_code'], $upUser);
//                        print_r($tzFyUser);die;
                            if($tzFyUser['should_user_id'] != 0){
//                                $firstTzRatio = $this->getBoUserSystemFirstRatio(2, 0, $tz, $qd); // 提点比例
                                $firstTzRatio = config('default_first_tz_ratio'); // 提点比例
                                $firstTzFy = $order['shou_price'] * $firstTzRatio / 100; // 分佣金额
                                $firstTzDesc = $userFirst['user_real_name'] . '首批款-佣金';

                                $this->insertBoFy($tzFyUser['user_id'], $order['shou_user_id'], $tzFyUser['should_user_id'], $tzFyUser['freeze_user_id'], 1, $firstTzDesc, 1, $firstTzFy, $tzFyUser['bo_balance'], 0, $tzFyUser['hf'], 1, $tzFyUser['freeze_name']);

                                Db::table('up_u_user')
                                    ->where('user_id', $tzFyUser['user_id'])
                                    ->inc('user_bo_fy_balance', $firstTzFy)
                                    ->inc('user_bo_total_fy_balance', $firstTzFy)
                                    ->update();
                            }
                            //*********************************   首批款分佣   end ********************//

                        }elseif ($order['shou_project_id'] == 2){
                            //*************************  补货款充值   start ****************************//
                            // 1.用户补货款
                            if($order['shou_remark']){
                                $descHuo = '补货款-' . $order['shou_remark'];
                            }else{
                                $descHuo = '补货款';
                            }

                            $this->insertBoInte($order['shou_user_id'], 1, $descHuo, $order['shou_price'], $user['user_bo_balance'], 0);

                            // 用户积分
                            Db::table('up_u_user')
                                ->where('user_id', $order['shou_user_id'])
                                ->inc('user_bo_total_balance', $order['shou_price'])
                                ->inc('user_bo_balance', $order['shou_price'])
                                ->inc('user_bo_huo_balance', $order['shou_price'])
                                ->update();
                            //*************************  补货款充值   end ****************************//

                            //*************************  团长分佣   start ****************************//
                            // 2.本团/上级分佣
                            $upHuoFyUser = $this->getBoUserSystemHuo(1, $user['user_bo_role'], $user['user_up_tz_code'], $user['user_up_up_tz_code']);
                            if($upHuoFyUser['should_user_id'] != 0){
//                                $huoTzFy1 = $huo_balance * $upHuoFyUser['ratio'] / 100; // 分佣金额
                                $huoTzFy1 = $order['shou_price'] * config('default_huo_tz_ratio') / 100; // 分佣金额
                                $descFyHuo1 = $user['user_real_name'] . '补货款-佣金';

                                $this->insertBoFy($upHuoFyUser['tz_user_id'], $order['shou_user_id'], $upHuoFyUser['should_user_id'], $upHuoFyUser['freeze_user_id'], 1, $descFyHuo1, 1, $huoTzFy1, $upHuoFyUser['bo_balance'], 0, $upHuoFyUser['hf'], 1, $upHuoFyUser['freeze_name']);

                                Db::table('up_u_user')
                                    ->where('user_id', $upHuoFyUser['tz_user_id'])
                                    ->inc('user_bo_fy_balance', $huoTzFy1)
                                    ->inc('user_bo_total_fy_balance', $huoTzFy1)
                                    ->update();
                            }

                            // 3.上级/上上级团队长分佣
                            $upUpHuoFyUser = $this->getBoUserSystemHuo(2, $user['user_bo_role'], $user['user_up_tz_code'], $user['user_up_up_tz_code']);
                            if($upUpHuoFyUser['should_user_id'] != 0){
//                                $huoTzFy2 = $huo_balance * $upUpHuoFyUser['ratio'] / 100; // 分佣金额
                                $huoTzFy2 = $order['shou_price'] * config('default_huo_tz_ratio') / 100; // 分佣金额
                                $descFyHuo2 = $user['user_real_name'] . '补货款-佣金';

                                $this->insertBoFy($upUpHuoFyUser['tz_user_id'], $order['shou_user_id'], $upUpHuoFyUser['should_user_id'], $upUpHuoFyUser['freeze_user_id'], 1, $descFyHuo2, 1, $huoTzFy2, $upUpHuoFyUser['bo_balance'], 0, $upUpHuoFyUser['hf'], 1, $upUpHuoFyUser['freeze_name']);

                                Db::table('up_u_user')
                                    ->where('user_id', $upUpHuoFyUser['tz_user_id'])
                                    ->inc('user_bo_fy_balance', $huoTzFy2)
                                    ->inc('user_bo_total_fy_balance', $huoTzFy2)
                                    ->update();
                            }
                            //*************************  团长分佣   end ****************************//

                            //*************************  代理分佣   start ****************************//
                            // 4.县代管理费
                            $quFyUser = $this->getDaiLiFy(3, $user['user_qu']);
                            if($quFyUser['should_user_id'] != 0){
//                                $huoDlFy3 = $huo_balance * $quFyUser['ratio'] / 100; // 分佣金额
                                $huoDlFy3 = $order['shou_price'] * config('default_qu_ratio') / 100; // 分佣金额
                                $descFyHuo3_dl = $user['user_real_name'] . '补货款-县管理费';

                                $this->insertBoFy($quFyUser['fy_user_id'], $order['shou_user_id'], $quFyUser['should_user_id'], 0, 1, $descFyHuo3_dl, 1, $huoDlFy3, $quFyUser['bo_balance'], 0, $quFyUser['hf'], 2, $quFyUser['freeze_name']);

                                Db::table('up_u_user')
                                    ->where('user_id', $quFyUser['fy_user_id'])
                                    ->inc('user_bo_fy_balance', $huoDlFy3)
                                    ->inc('user_bo_total_fy_balance', $huoDlFy3)
                                    ->update();
                            }

                            // 5.市代管理费
                            $shiFyUser = $this->getDaiLiFy(2, $user['user_shi']);
                            if($shiFyUser['should_user_id'] != 0){
//                                $huoDlFy2 = $huo_balance * $shiFyUser['ratio'] / 100; // 分佣金额
                                $huoDlFy2 = $order['shou_price'] * config('default_shi_ratio') / 100; // 分佣金额
                                $descFyHuo2_dl = $user['user_real_name'] . '补货款-市管理费';

                                $this->insertBoFy($shiFyUser['fy_user_id'], $order['shou_user_id'], $shiFyUser['should_user_id'], 0, 1, $descFyHuo2_dl, 1, $huoDlFy2, $shiFyUser['bo_balance'], 0, $shiFyUser['hf'], 3, $shiFyUser['freeze_name']);

                                Db::table('up_u_user')
                                    ->where('user_id', $shiFyUser['fy_user_id'])
                                    ->inc('user_bo_fy_balance', $huoDlFy2)
                                    ->inc('user_bo_total_fy_balance', $huoDlFy2)
                                    ->update();
                            }

                            // 6.省代管理费
                            $shengFyUser = $this->getDaiLiFy(1, $user['user_sheng']);
                            if($shengFyUser['should_user_id'] != 0){
//                                $huoDlFy1 = $huo_balance * $shengFyUser['ratio'] / 100; // 分佣金额
                                $huoDlFy1 = $order['shou_price'] * config('default_sheng_ratio') / 100; // 分佣金额
                                $descFyHuo1_dl = $user['user_real_name'] . '补货款-省管理费';

                                $this->insertBoFy($shengFyUser['fy_user_id'], $order['shou_user_id'], $shengFyUser['should_user_id'], 0, 1, $descFyHuo1_dl, 1, $huoDlFy1, $shengFyUser['bo_balance'], 0, $shengFyUser['hf'], 4, $shengFyUser['freeze_name']);

                                Db::table('up_u_user')
                                    ->where('user_id', $shengFyUser['fy_user_id'])
                                    ->inc('user_bo_fy_balance', $huoDlFy1)
                                    ->inc('user_bo_total_fy_balance', $huoDlFy1)
                                    ->update();
                            }
                            //*************************  代理分佣   end ****************************//
                        }elseif ($order['shou_project_id'] == 3){
                            // TODO:暂时没有该充值项
                        }elseif ($order['shou_project_id'] == 4){
                            //******************  特惠商品充值（不参与分佣）   start   **********************//
                            if($order['shou_remark']){
                                $desc_ms = '特惠商品款-' . $order['shou_remark'];
                            }else{
                                $desc_ms = '特惠商品款';
                            }

                            // 用户积分明细
                            $this->insertThInte($order['shou_user_id'], 1, $desc_ms, $order['shou_price'], $user['user_recharge_balance'], 0);

                            // 用户积分
                            Db::table('up_u_user')
                                ->where('user_id', $order['shou_user_id'])
                                ->inc('user_total_balance', $order['shou_price'])
                                ->inc('user_recharge_balance', $order['shou_price'])
                                ->update();
                            //******************  特惠商品充值（不参与分佣）   end   **********************//
                        }elseif ($order['shou_project_id'] == 5){
                            // TODO: 家大业大积分
                            //******************  家大业大充值（不参与分佣）   start   **********************//
                            if($order['shou_remark']){
                                $desc_big = '家大业大款-' . $order['shou_remark'];
                            }else{
                                $desc_big = '家大业大款';
                            }

                            // 用户积分明细
                            $this->insertBigInte($order['shou_user_id'], 1, $desc_big, $order['shou_price'], $user['user_big_balance'], 0);

                            // 用户积分
                            Db::table('up_u_user')
                                ->where('user_id', $order['shou_user_id'])
                                ->inc('user_big_total_balance', $order['shou_price'])
                                ->inc('user_big_balance', $order['shou_price'])
//                                ->inc('user_recharge_balance', $order['shou_price'])
                                ->update();
                            //******************  家大业大充值（不参与分佣）   end   **********************//
                        }elseif ($order['shou_project_id'] == 6){
                            // TODO:不计入积分
                        }elseif ($order['shou_project_id'] == 7){
                            //*************************  定金充值 （不参与分佣，充入其它款项）  start ****************************//
                            if($order['shou_remark']){
                                $descD = '定金-' . $order['shou_remark'];
                            }else{
                                $descD = '定金';
                            }

                            $this->insertBoInte($order['shou_user_id'], 1, $descD, $order['shou_price'], $user['user_bo_balance'], 0);

                            // 用户积分
                            Db::table('up_u_user')
                                ->where('user_id', $order['shou_user_id'])
                                ->inc('user_bo_total_balance', $order['shou_price'])
                                ->inc('user_bo_balance', $order['shou_price'])
                                ->inc('user_bo_other_balance', $order['shou_price'])
                                ->update();
                            //*************************  定金充值 （不参与分佣，充入其它款项）   end ****************************//
                        }

                        Db::commit();
                        $result = true;
                    }catch (\Exception $e){
                        Db::rollback();
                        $result = false;
                    }
                }else{
                    $result = true;
                }
            }elseif ($num_type == 5){
                $order = Db::table('up_private_buy_order')
                    ->join('up_u_user', 'user_id = order_user_id', 'LEFT')
                    ->where('order_no', $num)
                    ->field([
                        'order_user_id',
                        'order_ps_id',
                        'order_number',
                        'order_status',
                        'order_type',
                        'order_id',
                        'user_bo_role',
                        'user_up_tz_code',
                        'user_up_up_tz_code',
                        'user_real_name',
                        'order_total_price',
                        'user_qu',
                        'user_shi',
                        'user_sheng'
                    ])
                    ->find();

                if($order['order_status'] == 1){
                    $hasStock = Db::table('up_private_stock')
                        ->where(['stock_user_id' => $order['order_user_id'], 'stock_ps_id' => $order['order_ps_id']])
                        ->find();
                    Db::startTrans();
                    try{
                        // 库存
                        if($hasStock){
                            Db::table('up_private_stock')
                                ->where('stock_id', $hasStock['stock_id'])
                                ->inc('stock_number', $order['order_number'])
                                ->update();
                        }else{
                            Db::table('up_private_stock')
                                ->insert([
                                    'stock_user_id' => $order['order_user_id'],
                                    'stock_ps_id' => $order['order_ps_id'],
                                    'stock_number' => $order['order_number']
                                ]);
                        }

                        // 订单状态
                        Db::table('up_private_buy_order')
                            ->update([
                                'order_id' => $order['order_id'],
                                'order_status' => 2,
                                'order_pay_time' => date('Y-m-d H:i:s')
                            ]);

                        // 加盟商提成
                        if($order['order_type'] == 1){
                            //*************************  团长分佣   start ****************************//
                            // 2.本团/上级分佣
                            $upHuoFyUser = $this->getBoUserSystemHuo(1, $order['user_bo_role'], $order['user_up_tz_code'], $order['user_up_up_tz_code']);
                            if($upHuoFyUser['should_user_id'] != 0){
//                                $huoTzFy1 = $huo_balance * $upHuoFyUser['ratio'] / 100; // 分佣金额
                                $huoTzFy1 = $order['order_total_price'] * config('default_huo_tz_ratio') / 100; // 分佣金额
                                $descFyHuo1 = $order['user_real_name'] . '私人订制套餐-佣金';

                                $this->insertBoFy($upHuoFyUser['tz_user_id'], $order['order_user_id'], $upHuoFyUser['should_user_id'], $upHuoFyUser['freeze_user_id'], 1, $descFyHuo1, 1, $huoTzFy1, $upHuoFyUser['bo_balance'], 0, $upHuoFyUser['hf'], 1, $upHuoFyUser['freeze_name']);

                                Db::table('up_u_user')
                                    ->where('user_id', $upHuoFyUser['tz_user_id'])
                                    ->inc('user_bo_fy_balance', $huoTzFy1)
                                    ->inc('user_bo_total_fy_balance', $huoTzFy1)
                                    ->update();
                            }

                            // 3.上级/上上级团队长分佣
                            $upUpHuoFyUser = $this->getBoUserSystemHuo(2, $order['user_bo_role'], $order['user_up_tz_code'], $order['user_up_up_tz_code']);
                            if($upUpHuoFyUser['should_user_id'] != 0){
//                                $huoTzFy2 = $huo_balance * $upUpHuoFyUser['ratio'] / 100; // 分佣金额
                                $huoTzFy2 = $order['order_total_price'] * config('default_huo_tz_ratio') / 100; // 分佣金额
                                $descFyHuo2 = $order['user_real_name'] . '私人订制套餐-佣金';

                                $this->insertBoFy($upUpHuoFyUser['tz_user_id'], $order['order_user_id'], $upUpHuoFyUser['should_user_id'], $upUpHuoFyUser['freeze_user_id'], 1, $descFyHuo2, 1, $huoTzFy2, $upUpHuoFyUser['bo_balance'], 0, $upUpHuoFyUser['hf'], 1, $upUpHuoFyUser['freeze_name']);

                                Db::table('up_u_user')
                                    ->where('user_id', $upUpHuoFyUser['tz_user_id'])
                                    ->inc('user_bo_fy_balance', $huoTzFy2)
                                    ->inc('user_bo_total_fy_balance', $huoTzFy2)
                                    ->update();
                            }
                            //*************************  团长分佣   end ****************************//

                            //*************************  代理分佣   start ****************************//
                            // 4.县代管理费
                            $quFyUser = $this->getDaiLiFy(3, $order['user_qu']);
                            if($quFyUser['should_user_id'] != 0){
//                                $huoDlFy3 = $huo_balance * $quFyUser['ratio'] / 100; // 分佣金额
                                $huoDlFy3 = $order['order_total_price'] * config('default_qu_ratio') / 100; // 分佣金额
                                $descFyHuo3_dl = $order['user_real_name'] . '私人订制套餐-县管理费';

                                $this->insertBoFy($quFyUser['fy_user_id'], $order['order_user_id'], $quFyUser['should_user_id'], 0, 1, $descFyHuo3_dl, 1, $huoDlFy3, $quFyUser['bo_balance'], 0, $quFyUser['hf'], 2, $quFyUser['freeze_name']);

                                Db::table('up_u_user')
                                    ->where('user_id', $quFyUser['fy_user_id'])
                                    ->inc('user_bo_fy_balance', $huoDlFy3)
                                    ->inc('user_bo_total_fy_balance', $huoDlFy3)
                                    ->update();
                            }

                            // 5.市代管理费
                            $shiFyUser = $this->getDaiLiFy(2, $order['user_shi']);
                            if($shiFyUser['should_user_id'] != 0){
//                                $huoDlFy2 = $huo_balance * $shiFyUser['ratio'] / 100; // 分佣金额
                                $huoDlFy2 = $order['order_total_price'] * config('default_shi_ratio') / 100; // 分佣金额
                                $descFyHuo2_dl = $order['user_real_name'] . '私人订制套餐-市管理费';

                                $this->insertBoFy($shiFyUser['fy_user_id'], $order['order_user_id'], $shiFyUser['should_user_id'], 0, 1, $descFyHuo2_dl, 1, $huoDlFy2, $shiFyUser['bo_balance'], 0, $shiFyUser['hf'], 3, $shiFyUser['freeze_name']);

                                Db::table('up_u_user')
                                    ->where('user_id', $shiFyUser['fy_user_id'])
                                    ->inc('user_bo_fy_balance', $huoDlFy2)
                                    ->inc('user_bo_total_fy_balance', $huoDlFy2)
                                    ->update();
                            }

                            // 6.省代管理费
                            $shengFyUser = $this->getDaiLiFy(1, $order['user_sheng']);
                            if($shengFyUser['should_user_id'] != 0){
//                                $huoDlFy1 = $huo_balance * $shengFyUser['ratio'] / 100; // 分佣金额
                                $huoDlFy1 = $order['order_total_price'] * config('default_sheng_ratio') / 100; // 分佣金额
                                $descFyHuo1_dl = $order['user_real_name'] . '私人订制套餐-省管理费';

                                $this->insertBoFy($shengFyUser['fy_user_id'], $order['order_user_id'], $shengFyUser['should_user_id'], 0, 1, $descFyHuo1_dl, 1, $huoDlFy1, $shengFyUser['bo_balance'], 0, $shengFyUser['hf'], 4, $shengFyUser['freeze_name']);

                                Db::table('up_u_user')
                                    ->where('user_id', $shengFyUser['fy_user_id'])
                                    ->inc('user_bo_fy_balance', $huoDlFy1)
                                    ->inc('user_bo_total_fy_balance', $huoDlFy1)
                                    ->update();
                            }
                            //*************************  代理分佣   end ****************************//
                        }

                        Db::commit();
                        $result = true;
                    }catch (\Exception $e){
                        Db::rollback();
                        $result = false;
                    }
                }else{
                    $result = true;
                }
            }elseif($num_type == 6){
                $order = Db::table('up_order')->where('order_number', $num)->field('order_id, order_is_pay')->find();
                if($order['order_is_pay'] == 1){
                    $res = Db::table('up_order')
                        ->where('order_id', $order['order_id'])
                        ->update([
                            'order_is_pay' => 2,
                            'order_status' => 2,
                            'order_pay_time' => date('Y-m-d H:i:s')
                        ]);
                    if($res){
                        $result = true;
                    }else{
                        $result = false;
                    }
                }else{
                    $result = true;
                }
            }
        } else{
            $result = false;
        }
        // 返回状态给微信服务器----------------
        if ($result) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        exit();
        return $result;
    }

    /**
     * 回调---用于把回调内容写入文件
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = ROOT_PATH . '/public/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = json_encode($data, true);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }

    public function aaa(){
        $num = 'BZ_202303221531591593';
        $order = Db::table('up_bo_orderz')->where('boz_number', $num)
            ->field('boz_id, boz_status, boz_order_id, boz_no, boz_get_type, boz_user_id, boz_is_pay')->find();
        if($order['boz_is_pay'] == 1){
            $update_zeng = [
                'boz_id' => $order['boz_id'],
                'boz_is_pay' => 2,
                'boz_status' => 2,
                'boz_pay_time' => date('Y-m-d H:i:s'),
                'boz_get_month' => date('Y-m')
            ];

            $alreadyGet = Db::table('up_bo_orderz')
                ->where(['boz_order_id' => $order['boz_order_id'], 'boz_is_pay' => 2])
                ->sum('boz_no');
            if($alreadyGet + $order['boz_no'] == 11){
                $update_zeng['boz_eleven'] = '已领11盒面膜';
            }

            $giftbag_order = Db::table('up_bo_orderg')
                ->join('up_u_user', 'user_id = bog_user_id', 'LEFT')
                ->where('bog_id', $order['boz_order_id'])
                ->field('user_zeng_get_type, user_id')
                ->find();

            Db::startTrans();
            try{
                // 更新面膜订单信息
                Db::table('up_bo_orderz')->update($update_zeng);

                // 减剩余面膜数量
                Db::table('up_bo_orderg')->where('bog_id', $order['boz_order_id'])->setDec('bog_zeng_number', $order['boz_no']);

                // 确定用户面膜可领取的渠道
                if($giftbag_order['user_zeng_get_type'] == 0){
                    Db::table('up_u_user')->where('user_id', $giftbag_order['user_id'])->setField('user_zeng_get_type', $order['boz_get_type']);
                }

                Db::commit();
                $result = true;
            }catch (\Exception $e){
                Db::rollback();
                $result = false;
            }
        }else{
            $result = true;
        }
    }

}